package com.syz.web.JackSon;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.syz.web.pojo.Student;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class JSONDemo {

    //Java对象转换成JSON字符串
    @Test
    public void test1() throws JsonProcessingException {
        Student student = new Student(1, "张三", 23, "男",2,"上海");
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(student);
        System.out.println(json);
    }

    @Test
    public void test2() throws JsonProcessingException {
        Map<String, Object> map = new HashMap<>();
        map.put("id", 2);
        map.put("name", "李四");
        map.put("age", 23);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(map);
        System.out.println(json);
    }

    @Test
    public void test3() throws IOException {
        String json = "{\"id\":1,\"name\":\"张无\",\"age\":23,\"gender\":\"男\"}";
        ObjectMapper objectMapper = new ObjectMapper();
        Student student = objectMapper.readValue(json, Student.class);
        System.out.println(student);
    }
}
